iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
生成式 AI

nutc_imac_Agent拼裝車系列 第 23

Day23 Spring AI 整合本地模型:Ollama 實戰篇

  • 分享至 

  • xImage
  •  

延續前一篇《Spring AI 核心組件與設計理念》,
今天我們不再依賴雲端 API,而是在 本機端運行 AI 模型


一、什麼是 Ollama(前面雖然介紹過但我們再複習一下)?

Ollama 是一款可以在本地運行各種開源 LLM(如 Llama 3、Mistral、Phi 等)的工具,
支援 macOS、Linux、Windows(需 WSL2),可離線執行、免上雲端、資料不外流。

它最大的特點是:

  • 模型管理簡單(ollama pull llama3
  • 本地 REST API(http://localhost:11434
  • 支援多種開源模型(Llama、Mistral、Phi、Gemma…)

二、安裝與啟動 Ollama

安裝

前往官網下載安裝(https://ollama.ai/download)

或使用命令列安裝(macOS / Linux):

curl -fsSL https://ollama.com/install.sh | sh

啟動服務

Ollama 安裝後會自動啟動本地伺服器,預設埠號為 11434
你可以透過下列指令確認是否正常運作:

ollama list
ollama run llama3

第一次執行時會自動下載模型(需一些時間)。
執行成功後會進入互動模式,你可以輸入訊息測試模型是否能回覆。


三、在 Spring Boot 中整合 Ollama

接下來,我們要修改專案,讓 Spring AI 使用 Ollama 作為後端 Provider。

1. 新增依賴

pom.xml 加入 Ollama 依賴模組:

<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>

2. 修改設定檔 application.yml

spring:
  ai:
    ollama:
      base-url: http://10.0.0.207:11434

這樣就設定好 Spring AI 的 Ollama 客戶端了!


四、建立 ChatController(使用本地模型)

package com.example.it_spring_chat;

import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/api")
public class ChatController {
    
    @PostMapping("/chat")
    public String chat(@RequestParam String message) {
                var ollamaApi = OllamaApi.builder().baseUrl("baseUR").build();


        var chatModel  = OllamaChatModel.builder()
                .ollamaApi(ollamaApi)
                .defaultOptions(
                        OllamaOptions.builder()
                                .model("gemma3:12b")
                                .temperature(0.9)
                                .build())
                .build();


        ChatResponse response = chatModel.call(
                new Prompt(message));

        return response.getResult().getOutput().getText();
    }
}

執行應用後,你可以呼叫:

http://10.0.0.207:8080/api/chat?message=介紹一下你自己

💬 回覆就會由你本機的模型生成!


五、串流輸出

如果想要用串流輸出則可以使用.stream()

// Or with streaming responses
Flux<ChatResponse> response = chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

六、常見問題與最佳實踐

問題 原因 解法
Connection refused Ollama 沒啟動 執行 ollama serve 啟動伺服器
回覆速度慢 模型初次載入或 VRAM 不足 先行預載模型,或使用輕量模型(如 phi3)
CPU 占用高 預設使用 GPU/CPU 混合模式 可設定環境變數 OLLAMA_NUM_THREADS 調整

下一篇預告:Day24|RAG 實戰篇:整合 Spring AI 與向量資料庫

下一篇我們將進一步讓你的應用具備「知識檢索能力」,
使用 Spring AI + Redis VectorStore 建立一個本地知識查詢 AI


上一篇
Day 22 Spring AI : 打造你的第一個 AI 聊天服務
下一篇
Day24 RAG 實戰篇 (一):認識 Retrieval-Augmented Generation
系列文
nutc_imac_Agent拼裝車25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言